<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/treetable/jquery.treetable.css"/>
    <link rel="stylesheet" href="/css/treetable/jquery.treetable.theme.default.css"/>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap-select.min.css">
    <link rel="stylesheet" type="text/css" href="/at-js/css/jquery.atwho.css">
    <script src="/js/libs/jquery-2.1.1.min.js"></script>
    <script src="/js/bootstrap/bootstrap.min.js"></script>
    <script src="/js/bootstrap/bootstrap-select.min.js"></script>
    <script src="/js/jq.js"></script>
    <script src="/js/plugin/bootstrapvalidator/bootstrapValidator.min.js"></script>
    <script src="/js/common.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/dict.js"></script>
    <script src="/js/libs/jquery.ztree.all-3.5.min.js"></script>
    <script src="/js/my/ztree-menu.js"></script>
    <script src="/js/my/permission.js"></script>
    <script src="/js/plugin/datatables/jquery.dataTables.min.js"></script>
    <script src="/js/plugin/datatables/dataTables.bootstrap.min.js"></script>
    <script src="/js/libs/jquery.treetable.js"></script>
    <script src="/js/plugin/jquery-caret/jquery.caret.js"></script>
    <script src="/at-js/js/jquery.atwho.js"></script>
</head>
<body>
<div class="col-xs-12 col-sm-12 col-md-6 col-lg-6 col-md-offset-2 col-lg-offset-2">
    <form class="form-horizontal" onsubmit="return false" id="form">
        <fieldset>
            <input type="hidden" id="projectId" name="projectId">
            <div class='form-group'>
                <label class='col-md-4 control-label'>任务名称</label>
                <div class='col-md-8'>
                    <input class='form-control' placeholder='任务名称' type='text' name='name' id='name' >
                </div>
            </div>

            <div class='form-group'>
                <label class='col-md-4 control-label'>执行者：</label>
                <div class='col-md-8'>
                    <input class='form-control' type='hidden' name='participantId' id='participantId'
                           data-bv-notempty='true' data-bv-notempty-message='执行者 不能为空'>
                    <input style="width: 90%;float: left;" class='form-control' placeholder='执行者' type='text'
                           name='participantName' id='participantName' readonly>
                    <button style="width: 10%;float: right; height: 32px; line-height: 32px;"
                            class="layui-btn layui-btn-sm"
                            onclick="projectList()">
                        <i class="layui-icon">&#xe615;</i>
                    </button>
                </div>
            </div>
            <div class='form-group'>
                <label class='col-md-4 control-label'>预计工时：</label>
                <div class='col-md-8'>
                    <input class="form-control" placeholder="预计工时" name="estimateWorkingHours" id="estimateWorkingHours" >
                </div>
            </div>
            <div class='form-group'>
                <label class='col-md-4 control-label'>任务描述：</label>
                <div class='col-md-8'>
                    <div class="panel panel-default" name="description" id="description" contenteditable="true"
                         style="width: 100%; min-height: 100px;"></div>
                </div>
            </div>
            <div class='form-group'>
                <label class='col-md-4 control-label'>截止日期</label>
                <div class='col-md-8'>
                    <input class='form-control' placeholder='截止日期' type='text' name='deadline' id='deadline' >
                </div>
            </div>
            <div class='form-group'>
                <label class='col-md-4 control-label'>优先级:</label>
                <div class='col-md-8'>
                    <select class="form-control input-sm selectpicker show-tick" name="grade" id="grade"
                            title="任务状态" data-live-search="true"></select>
                </div>
            </div>
            <!--<div class='form-group'>-->
                <!--<label class='col-md-4 control-label'>任务状态:</label>-->
                <!--<div class='col-md-8'>-->
                    <!--<select class="form-control input-sm selectpicker show-tick" name="status" id="status"-->
                            <!--title="任务状态" data-live-search="true"></select>-->
                <!--</div>-->
            <!--</div>-->
            <div class='form-group'>
                <label class='col-md-4 control-label'>附件</label>
                <div class="layui-upload col-md-8">
                    <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="selectScreenshotPath">
                        选择多文件
                    </button>
                    <input type="hidden" value="" id="screenshotPath" name="screenshotPath">
                    <button type="button" class="layui-btn layui-btn-sm" id="uploadScreenshotPath">开始上传</button>
                    <div class="layui-upload-list">
                        <table class="layui-table">
                            <thead>
                            <tr>
                                <th>文件名</th>
                                <th>大小</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody id="screenshotPathList"></tbody>
                        </table>
                    </div>
                </div>
            </div>
            <div class="form-actions">
                <div class="row" align="center">
                    <div class="col-md-12">
                        <button class="btn btn-primary" type="submit" onclick="save()">
                            <i class="fa fa-save"></i> 保存
                        </button>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
</div>
<script type="text/javascript">
    // 设置验证规则
    var validatorSettings = {
        message: '验证不通过',
        fields: {
            name: {
                message: '任务名称验证失败',
                validators: {
                    notEmpty: {
                        message: '任务名称不能为空'
                    }
                }
            },
            participantName: {
                message: '执行者验证失败',
                validators: {
                    notEmpty: {
                        message: '执行者不能为空'
                    }
                }
            },
            estimateWorkingHours: {
                message: '预计工时验证失败',
                validators: {
                    notEmpty: {
                        message: '预计工时不能为空'
                    },numeric: {
                        message: '预计工时只能包含数字'
                    },greaterThan: {
                        value: 0,
                        message: '预计工时必须为正数'
                    },
                    lessThan: {
                        value: 9999,
                        message: '预计工时必须小于10000'
                    }
                }
            },
            deadline: {
                message: '截止日期验证失败',
                validators: {
                    notEmpty: {
                        message: '截止日期不能为空'
                    }
                }
            }
        },
        submitHandler: function (validator, form, submitButton) {
            alert("submit");
        }
    };

    $(function () {
        $('#form').bootstrapValidator(validatorSettings);
        runAt();
    });

    layui.use(['layer', 'laydate', 'upload'], function () {
        var layer = layui.layer;
        var laydate = layui.laydate;
        var upload = layui.upload;

        laydate.render({
            elem: '#deadline',
            done: function (value, date, endDate) {
                // console.log(value); //得到日期生成的值，如：2017-08-18
                // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                // console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
            }
        });

        var screenshotPathListView = $('#screenshotPathList');
        var uploadListIns = upload.render({
            elem: '#selectScreenshotPath'
            , url: '/files'
            , accept: 'file'
            , multiple: true
            , auto: false
            , bindAction: '#uploadScreenshotPath'
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td style ="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // 重新获得所有上传文件
                        $('#screenshotPath').val('');
                        $('.screenshotPathFile').each(function () {
                            $('#screenshotPath').val($('#screenshotPath').val() + '|' + $(this).data('id'));
                        });
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    screenshotPathListView.append(tr);
                });
            }
            , done: function (res, index, upload) {
                if (res.code === 0) { //上传成功
                    var tr = screenshotPathListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(0).html('<a target="_blank" data-id="' + res.data.id + '" class="screenshotPathFile" href="/files' + res.data.url + '">' + res.data.fileName + '</a>');
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    // tds.eq(3).html(''); //清空操作

                    // 追加文件id
                    $('#screenshotPath').val($('#screenshotPath').val() + '|' + res.data.id);
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = screenshotPathListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });
    });
    var pers = checkPermission();

    var status = showDictSelect('status', 'task_status', '', '0');
    var grade = showDictSelect('grade', 'dept_level', '', '1');

    var projectId = getUrlParam('projectId');
    function projectList(){
        let flushFields = ['participantId:id', 'participantName:nickname'];
        let path = '/pages/user/userTableForTms.html?isAll=true&isMultiSelect=false&projectId=' + projectId;
        let echo = []; //传输的数组
        let count = 0; //传输的数组长度
        let val = $('#' + flushFields[0].split(':')[0]).val().trim();
        if (val) {
            count = val.split(';').length;
        }

        for (let i = 0; i < count; i++) {
            let item = {};
            $.each(flushFields, function (j, field) {
                let formField = field.split(':')[0];
                let entityField = field.split(':')[1];
                item[entityField] = $('#' + formField).val().split(';')[i];
            });
            echo[i] = item;
        }

        path += '&echo=' + encodeURIComponent(JSON.stringify(echo));

        layer.open({
            type: 2,
            title: '任务成员列表',
            shadeClose: true, //是否点击阴影关闭层
            area: [($(window).width() * 0.8) + 'px', ($(window).height() - 30) + 'px'],
            offset: 'auto', //rb右下角弹出
            anim: 0,
            content: [path, 'yes'], //iframe的url，no代表不显示滚动条
            fixed: true, // 是否固定
            maxmin: true,
            btn: ['确定', '清除', '取消'],
            yes: function (index, layero) {
                // let rows = layero.find("iframe")[0].contentWindow.example.rows('.success').data();
                let selectedItems = $(layero.find("iframe")[0]).contents().find('[name=selectedItem]');
                if (flushFields) {
                    $.each(selectedItems, function (rowIndex, item) {
                        $.each(flushFields, function (fieldIndex, flushFiled) {
                            let fieldsPair = flushFiled.split(':');
                            if (rowIndex === 0) {
                                $('#' + fieldsPair[0].trim()).val($(item).data(fieldsPair[1].trim()));
                            } else {
                                $('#' + fieldsPair[0].trim()).val($('#' + fieldsPair[0].trim()).val().trim() + ';' + $(item).data(fieldsPair[1].trim()));
                            }
                        });
                    })
                }

                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
                layer.close(index); //如果设定了yes回调，需进行手工关闭
            },
            cancel: function (index, layero) {
                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
            },
            btn2: function (index, layero) {
                if (flushFields) {
                    $.each(flushFields, function (index, item) {
                        $('#' + item.split(':')[0]).val('');
                    });
                }
                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
            }
        });
    }

    $('#projectId').val(projectId);

    function save() {
        $('#form').bootstrapValidator(validatorSettings);
        var bootstrapValidator = $("#form").data('bootstrapValidator');
        bootstrapValidator.validate();
        if (!bootstrapValidator.isValid()) {
            return;
        }

        var formdata = $("#form").serializeObject();
        formdata.description = $('#description').html();
        formdata.atUsers = [];

        $.each($('#form').find('[name=atUsers]'), function (index, item) {
            formdata.atUsers[index] = $(item).data("id");
        });

        $.ajax({
            type: 'post',
            url: '/task/',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(formdata),
            success: function (data) {
                layer.msg("添加成功", {shift: -1, time: 1000}, function () {
                    parent.location.reload();
                });
            }
        });
    }

    function runAt() {
        var users = [];

        $.ajax({
            type: 'get',
            url: '/users/partList/'+ projectId,
            async: false,
            success: function (json) {
                if (json.code === 0) {
                    users = json.data;
                }
            }
        });

        let offset = top.getIFrameOffset();

        offset.top -= 65;

        var at_config = {
            at: "@",
            data: users,
            searchKey: 'nickname',
            headerTpl: '<div class="atwho-header">User List<small>↑&nbsp;↓&nbsp;</small></div>',
            insertTpl: '<span data-id="${id}" name="atUsers">@${nickname}</span>',
            displayTpl: "<li>${nickname} <small>${username}</small></li>",
            limit: 5,
            offset: offset
        };

        var $inputor = $('#description').atwho(at_config);
        // $inputor.caret('pos', 47);
        // $inputor.focus().atwho('run');
    }

</script>
</body>
</html>
